#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import os

def vp_psv2sv(psv_path,sv_path):
	psv_code = open(psv_path,"r")
	psv_code_gen = open(sv_path,"w")
	
	sys_stdout = sys.stdout
	sys.stdout = psv_code_gen
	
	line = psv_code.readline()
	while line:
		psv_begin_str = line.strip().replace("\n","")
		if psv_begin_str == "`psv_begin":
			pycode_line = psv_code.readline()
			pycode = []
			psv_end_str = pycode_line.strip().replace("\n","")
			
			while psv_end_str != "`psv_end":
				pycode.append(pycode_line)
				pycode_line = psv_code.readline()
				psv_end_str = pycode_line.strip().replace("\n","")
			
			pycode_src = "".join(pycode)
			
			# execute Python code
			exec(pycode_src)
		else:
			psv_code_gen.write(line)
		
		line = psv_code.readline()
	
	psv_code.close()
	psv_code_gen.close()
	
	sys.stdout = sys_stdout

work_space_dir = sys.argv[1]

if work_space_dir == "":
	print("ERRO NO WORKSPACE DIR")
	exit(1)

psrc_fl_dir = work_space_dir + "/src/psvfilelist.f" # source code file list directory
src_file_list   = []
gen_file_list	= []
pv_fl = open(psrc_fl_dir,"r")

line = pv_fl.readline()
while line:
	lc = line.strip().replace("\n","")
	if lc == "":
		line = pv_fl.readline()
		continue
	if lc[0] == "#":
		line = pv_fl.readline()
		continue
	rsrc_path = lc.replace("${workspace}",work_space_dir)
	src_file_list.append(rsrc_path)
	pv_fname  = rsrc_path[rsrc_path.rfind('/')+1:len(rsrc_path)]
	gen_file_list.append(work_space_dir + "/src/gen/" + pv_fname[0:pv_fname.rfind('.')] + ".sv")
	line = pv_fl.readline()

if not os.path.exists(work_space_dir + "/src/gen"):
	os.makedirs(work_space_dir + "/src/gen")

for i in range(len(src_file_list)):
	print("INFO\tgenerate %s"%gen_file_list[i])
	vp_psv2sv(src_file_list[i],gen_file_list[i])


